<?php

namespace app\api\controller;

use app\common\BaseApiController;
use app\api\middleware\Auth as MiddlewareAuth;

class Store extends BaseApiController
{

    protected $middleware = [
        MiddlewareAuth::class => [
            'except' => ['detail', 'list']
        ]
    ];

    public function detail($id)
    {
        $store = \app\model\Store::where(['id' => $id])->find();

        if (!$store) {
            return json(['code' => 400, 'msg' => '店铺不存在']);
        }

        if ($store['status'] == 0) {
            return json(['code' => 400, 'msg' => '店铺未审核']);
        }

        if ($store['status'] == 2) {
            return json(['code' => 400, 'msg' => '店铺已下架']);
        }

        return json(['code' => 200, 'msg' => 'success', 'data' => $store]);
    }

    public function list($pageNum = 1, $pageSize = 10)
    {
        $storeList = \app\model\Store::order('id', 'desc')->where("status", 1)->page($pageNum, $pageSize)->select();
        $total = \app\model\Store::where("status", 1)->count();
        return json(['code' => 200, 'msg' => 'success', 'data' => ['list' => $storeList, 'total' => $total]]);
    }

    public function submitAudit()
    {
        // 判断当前用户是否已存在店铺
        $store = \app\model\Store::where(['uid' => $this->request->uid])->find();
        if ($store) {
            return json(['code' => 400, 'msg' => '您已存在店铺，无需重复提交']);
        }

        $data = $this->request->post();

        $validate = new \app\validate\StoreAudit();
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        $store = new \app\model\Store();
        $store->name = $data['name'];
        $store->image = $data['image'];
        $store->address = $data['address'];
        $store->phone = $data['phone'];
        $store->status = 0; // 初始状态为待审核

        $store->uid = $this->request->uid;

        $result = $store->save();


        if ($result) {
            return json(['code' => 200, 'msg' => '店铺提交审核成功']);
        }

        return json(['code' => 400, 'msg' => '店铺提交审核失败']);
    }
}
